// pages/city/city.js
var bmap = require('../../libs/bmap-wx.min.js');
var wxMarkerData = [];
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		tat: 'true',
		key: '',
		num: 1,
		data: [],
		nan: false,
		city: '',
		cd: '',
		http: getApp().globalData.map,
		juli: '',
		cityListId: '',
		pd: 'false',
		citylist: '',
		letter: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
			"V", "W", "X", "Y", "Z"
		],
	},
	onPageScroll(e) {
		console.log(e)
	},
	ovo() {
		if (this.data.pd == 'false') {
			let a = this.data.num + 1
			this.setData({
				num: a
			})
			this.geo()
		}
	},
	numT(e) {
		this.setData({
			key: e.detail.value
		})
	},
	nue(e) {
		this.setData({
			nan: e.target.dataset.n
		})
	},
	onLoad: function(options) {
		let _this = this
		wx.request({
			url: getApp().globalData.http + 'action=getArea',
			success: (e) => {
				console.log(e)
				let a = []
				e.data.data.forEach(function(item, index) {
					item.Alist.forEach(function(item1, index1) {
						a.push(item1)
					})
				})
				let c = []
				for (let i = 0; i < _this.data.letter.length; i++) {
					c[i] = []
					for (let d = 0; d < a.length; d++) {
						if (_this.data.letter[i] == a[d].first) {
							c[i].push(a[d])
						}
					}
				}
				console.log(c)
				_this.setData({
					citylist: c,
				})
			}
		})
		var that = this;
		wx.showToast({
			title: '加载中',
			icon: 'loading'
		});
		var BMap = new bmap.BMapWX({
			ak: 'GSEHM6rV9bIquAHVUuLLxYHTThvGAW5l'
		});
		var success = function(data) {
			console.log(data)
			wxMarkerData = data.wxMarkerData;
			let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
			    let x = wxMarkerData[0].longitude;
			    let y = wxMarkerData[0].latitude;
			    let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
			    let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
			    let lngs = z * Math.cos(theta) + 0.0065;
			    let lats = z * Math.sin(theta) + 0.006;
			that.setData({
				city: data.originalData.result.addressComponent.city
			});
			that.setData({
				latitude: lats
			});
			that.setData({
				longitude: lngs
			});
			console.log(that.data.longitude)
			console.log(that.data.latitude)
			wx.request({
				url: getApp().globalData.http + 'action=getShopList&city=' + that.data.city +
					'&key=' + that.data.key + '&Longitude=' + lngs + '&Latitude=' + lats +
					'&pg=' +
					that.data.num,
				success: (res) => {
					console.log(res)
					let g = that.data.data
					let juli1 = []
					for (let i = 0; i < res.data.data.length; i++) {
						res.data.data[i].FenShu=Math.floor(res.data.data[i].FenShu)
						let a = String(res.data.data[i].juli).split('.')[0] / 1000
						if(a>1){
							juli1.push(String(a).slice(0, 3)+'km')
						}else{
							a=a*1000
							juli1.push(String(a).slice(0, 3)+'m')
						}
						g.push(res.data.data[i])
					}
					console.log(juli1)
					that.setData({
						data: g,
						juli: juli1,
					})
					if (that.data.data.length == 0) {
						that.setData({
							tat: 'false'
						})
					} else {
						that.setData({
							tat: 'true'
						})
					}
					if (res.data.data.length < 15) {
						that.setData({
							pd: 'true'
						})
					}
					wx.hideToast();
				}
			})
		}
		BMap.regeocoding({
			success: success,
		});
	},
	sou() {
		this.geo()
	},
	//定位方法
	getUserLocation: function() {
		var _this = this;
		wx.getSetting({
			success: (res) => {
				if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
					//未授权
					wx.showModal({
						title: '请求授权当前位置',
						content: '需要获取您的地理位置，请确认授权',
						success: function(res) {
							if (res.cancel) {
								//取消授权
								wx.showToast({
									title: '拒绝授权',
									icon: 'none',
									duration: 1000
								})
								wx.navigateBack({
									delta: 1
								})
							} else if (res.confirm) {
								//确定授权，通过wx.openSetting发起授权请求
								wx.openSetting({
									success: function(res) {
										if (res.authSetting["scope.userLocation"] == true) {
											wx.showToast({
												title: '授权成功',
												icon: 'success',
												duration: 1000
											})
											//再次授权，调用wx.getLocation的API
											_this.geo();
										} else {
											wx.showToast({
												title: '授权失败',
												icon: 'none',
												duration: 1000
											})
										}
									}
								})
							}
						}
					})
				} else if (res.authSetting['scope.userLocation'] == undefined) {
					//用户首次进入页面,调用wx.getLocation的API
					_this.geo();
				} else {
					//调用wx.getLocation的API
					_this.geo();
				}
			}
		})

	},

	// 获取定位城市
	geo: function(e) {
		var _this = this;
		wx.request({
			url: getApp().globalData.http + 'action=getShopList&city=' + _this.data.city +
				'&key=' + _this.data.key + '&Longitude=' + this.data.longitude + '&Latitude=' + this.data.latitude +
				'&pg=' +
				_this.data.num,
			success: (res) => {
				let g = _this.data.data
				let juli1 = []
				console.log(res)
				for (let i = 0; i < res.data.data.length; i++) {
					res.data.data[i].FenShu=Math.floor(res.data.data[i].FenShu)
					let a = String(res.data.data[i].juli).split('.')[0] / 1000
					if(a>1){
						juli1.push(String(a).slice(0, 3)+'km')
					}else{						console.log(a)
						juli1.push(String(a).slice(0, -3)+'m')
					}
					g.push(res.data.data[i])
				}
				if (res.data.data.length < 15) {
					_this.setData({
						pd: 'true'
					})
				}
				_this.setData({
					data: g,
					juli: juli1,
				})
				if (_this.data.data.length == 0) {
					_this.setData({
						tat: 'false'
					})
				} else {
					_this.setData({
						tat: 'true'
					})
				}
			}
		})
	},
	radioChange(e) {
		console.log(e)
		let a = e.detail.value.split('=')
		this.setData({
			cd: a
		})
	},
	tz() {
		if (this.data.cd != '') {
			let pages = getCurrentPages(); // 当前页的数据，可以输出来看看有什么东西
			let prevPage = pages[pages.length - 2];
			prevPage.setData({
				value: this.data.cd,
			})
			console.log(this.data.cd)
			wx.navigateBack({
				delta: 1
			})
		}else{
			wx.showToast({
				icon:'none',
				title:'请选择门店'
			})
		}
	},




































	cityTap(e) {

		const val = e.currentTarget.dataset.val || '',
			types = e.currentTarget.dataset.types || '',
			Index = e.currentTarget.dataset.index || '',
			that = this;
		console.log(types, val)
		let city = this.data.citySel;
		switch (types) {
			case 'locate':
				//定位内容
				city = this.data.locateCity;
				break;
			case 'national':
				//全国
				city = '全国';
				break;
			case 'new':
				//热门城市
				city = val;
				break;
			case 'list':
				//城市列表
				city = val.names;
				break;
		}
		if (city) {
			this.setData({
				data: [],
				city: city,
				num: 1,
				pd: 'false'
			})
			this.geo(city)
			this.setData({
				nan: false,
				city: city
			})
		} else {
			console.log('还没有');
			this.getLocate();
		}

	},
	//点击城市字母
	letterTap(e) {
		const Item = e.currentTarget.dataset.item;
		this.setData({
			cityListId: Item
		});
		console.log(Item);
	},
	ready() {
		console.log(getApp());
		let that = this,
			cityOrTime = wx.getStorageSync('locatecity') || {},
			time = new Date().getTime(),
			city = '';
		if (!cityOrTime.time || (time - cityOrTime.time > 1800000)) { //每隔30分钟请求一次定位
			// this.getLocate();
		} else { //如果未满30分钟，那么直接从本地缓存里取值
			that.setData({
				locateCity: cityOrTime.city
			})
		}
	}
})
